package com.sudo.demo.security.handler;

import com.demo.common.base.pojo.JsonRes;
import com.sudo.demo.security.util.GsonUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * AccessDeineHandler 用来解决认证过的用户访问无权限资源时的异常
 * @author zhaoxg on 2023年04月18日 10:43
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        JsonRes<String> jsonRes = JsonRes.errorMsg(accessDeniedException.getMessage());
        String json = GsonUtil.simpleObjToJson(jsonRes);
        response.getWriter().write(json);
    }
}
